﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

using dotUML.Core.Common;
using dotUML.Core.Common.SequenceDiagram;

namespace dotUML.Core.Parser.SequenceDiagram
{
    /// <summary>
    /// Lifelines parser class.
    /// </summary>
    class LifelinesParser : SequenceDiagramElementParser, ILifelinesParser
    {
        #region ILifelinesParser Members

        /// <summary>
        /// Parse lifeline.
        /// </summary>
        /// <param name="Xml">Xml block.</param>
        /// <returns>True if parsing was successful, otherwise - false.</returns>
        public bool ParseLifeline(XElement Xml)
        {
            string lifelineName, dataType; 
            ELifelineType lifelineType;
            List<IStereotype> stereotypes;

            ISequenceDiagram sequenceDiagram = Model.GetSequenceDiagram(DiagramName);

            lifelineName = ParseStringAttribute(Constants.Common.NameAttribute, Xml);

            if (sequenceDiagram.GetLifeline(lifelineName) != null)
            {
                throw new ParserException(string.Format(Resources.LifelineParser_ParseLifeline_LifelineExists, lifelineName));
            }

            dataType = ParseStringAttribute(Constants.SequenceDiagram.DataTypeAttribute, Xml, true);
            lifelineType = (ELifelineType)ParseEnumAttribute(Constants.Common.TypeAttribute, Xml, typeof(ELifelineType));
            stereotypes = ParseStereotypeAttribute(Constants.Common.StereotypesAttribute, Xml);

            ILifeline lifeline = sequenceDiagram.AddLifeline(lifelineName, lifelineType);
            lifeline.DataType = dataType;
            lifeline.Stereotypes = stereotypes;

            return true;
        }

        #endregion

        /// <summary>
        /// Parse a lifelines element and create appropriate items in the dotUML model.
        /// </summary>
        /// <param name="Xml">Xml lifelines block.</param>
        /// <param name="Model">dotUML model.</param>
        /// <returns>True if parsing is succsessful, otherwise false.</returns>
        public override bool Parse(string Xml, IModel Model)
        {
            bool result = true;
            this.Model = Model;

            try
            {
                XElement lifelines = XElement.Parse(Xml);
                foreach (XElement lifeline in lifelines.Elements(Constants.SequenceDiagram.LifelineNode))
                {
                    result = ParseLifeline(lifeline);
                    if (!result) break;
                }
            }
            catch (Exception ex)
            {
                result = false;
                NewError(EErrorType.Error, string.Format(Resources.LifelinesParser_Parse_Error, ex.Message));
                // TODO: Log exception
            }

            return result;
        }
    }
}
